//
//  MyViewController.m
//  SportGo
//
//  Created by rimi on 16/9/20.
//  Copyright © 2016年 Yrzteam. All rights reserved.
//

#import "MyViewController.h"
#import "PersonMessageViewController.h"
#import "SDImageCache.h"
#import "YJAboutUsViewController.h"
#import "YJSportsCircleViewController.h"
#import "YJMyAchievementViewController.h"
#import "YJPushSetViewController.h"
#import "YJLoginPageViewController.h"
#import "YJSuggestionViewController.h"
#import "UIButton+WebCache.h"
#import <ShareSDK/ShareSDK.h>
#import "YJMyViewCell.h"
#import "MBHUDDIY.h"
//获取屏幕设度，高度
#define kScreenHight [UIScreen mainScreen].bounds.size.height
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define headViewH    kScreenWidth/3*2
#define headH        kScreenWidth/4
@interface MyViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSArray *dataSource;
@property (nonatomic,strong) NSArray *picSource;
@property (nonatomic,strong) NSArray *nondataSource;
@property (nonatomic,strong) NSArray *nonpicSource;

@property (nonatomic,strong) NSMutableArray *allInfo;
@property (nonatomic,strong) NSMutableArray *allPic;
@property (nonatomic,strong) UIImageView *headButton;
@property (nonatomic,strong) UILabel *nameLabel;
@property (nonatomic,strong) UILabel *personalizedLabel;//个性签名
@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic,strong) UIView *backGround;
@property (nonatomic,assign)CGFloat scale;
@property (nonatomic,assign) BOOL isLogin;
@end

@implementation MyViewController
- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    
    if ( [[NSUserDefaults standardUserDefaults]boolForKey:@"isLogin"]) {
        _isLogin = YES;
        
     [[NSNotificationCenter defaultCenter] postNotificationName:@"refush" object:nil];
        
    }else{
        _isLogin = NO;
    }
   

}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];
     _dataSource = @[@[@"我的成就"],@[@"意见反馈",@"关于我们",@"清除缓存",@"推送设置"],@[@"退出登录"]];
    _picSource = @[@[@"成就"],@[@"建议",@"关于我们",@"清除缓存",@"推送"],@[@""]];
    
    //未登录的datasource
    _nondataSource = @[@[@"我的成就"],@[@"意见反馈",@"关于我们",@"清除缓存",@"推送设置"]];
    _nonpicSource = @[@[@"成就"],@[@"建议",@"关于我们",@"清除缓存",@"推送"]];

    _allInfo = _nondataSource.mutableCopy;
    _allPic = _nonpicSource.mutableCopy;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:self.tableView];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refushUI) name:@"refush" object:nil];
    [self addUI];
}
- (void)addUI {
    self.tableView.contentInset = UIEdgeInsetsMake(headViewH, 0, 0, 0);
   
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,-headViewH, kScreenWidth, headViewH)];
    _imageView.tag = 555;
    _imageView.image = [UIImage imageNamed:@"myBack"];
    
    _imageView.userInteractionEnabled = YES;
    self.scale = _imageView.bounds.size.width/_imageView.bounds.size.height;
    //头像
    _headButton = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, headH, headH)];
    _headButton.center = _imageView.center;
    _headButton.layer.cornerRadius = headH/2;
    _headButton.layer.masksToBounds = YES;
    _headButton.layer.borderWidth = 1;
    _headButton.layer.borderColor = [UIColor whiteColor].CGColor;
    _headButton.image = [UIImage imageNamed:@"游客2"];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(chooseTheHeadImage)];
    [_headButton addGestureRecognizer:tap];
    _headButton.userInteractionEnabled = YES;
    
    
    //用户名
    _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 170*bi, self.view.bounds.size.width, 30*bi)];
    _nameLabel.textAlignment = NSTextAlignmentCenter;
    _nameLabel.textColor = [UIColor whiteColor];
    _nameLabel.text = @"游客";
    _nameLabel.font = [UIFont systemFontOfSize:18];
    
    //个性签名
    _personalizedLabel = [[UILabel alloc] initWithFrame:RzCGRectMake(87, 200, 200, 25)];
    _personalizedLabel.text = @"这是一个空的签名,不错哟";
    _personalizedLabel.font = [UIFont systemFontOfSize:12];
    _personalizedLabel.textColor = [UIColor whiteColor];
    _personalizedLabel.textAlignment = NSTextAlignmentCenter;
    
    //编辑资料
    
    [_imageView addSubview:_nameLabel];
    [_imageView addSubview:_personalizedLabel];
    [self.tableView addSubview: _imageView];
    [self.tableView addSubview: _headButton];

 
  
}

#pragma mark -- button click
- (void)editUserMessage{
    
    if (_isLogin) {
        //登录
       PersonMessageViewController *personMessageVC = [[PersonMessageViewController alloc] init];

         [self.navigationController pushViewController:personMessageVC animated:YES];
    }else{
        YJLoginPageViewController *loginPageVC = [[YJLoginPageViewController alloc] init];
        [self.navigationController pushViewController:loginPageVC animated:YES];
    }
   
}

//进入个人资料页面
- (void)chooseTheHeadImage{
    if (_isLogin) {
        //登录
        PersonMessageViewController *personMessageVC = [[PersonMessageViewController alloc] init];
        
        [self.navigationController pushViewController:personMessageVC animated:YES];
    } else{
        YJLoginPageViewController *loginPageVC = [[YJLoginPageViewController alloc] init];
        [self.navigationController pushViewController:loginPageVC animated:YES];
    }
    
}
#pragma mark -- uitableview delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return _allInfo.count;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSArray *array = _allInfo[section];
    return array.count;

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *space = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 10)];
    space.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1];
    return space;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    YJMyViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mycell"];
    
    NSArray *array = _allInfo[indexPath.section];
    NSArray *pic = _allPic[indexPath.section];

 
    if (indexPath.section != 2) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.section == 2) {
        

        cell.headTitleLabel.textAlignment = NSTextAlignmentCenter;
        cell.headTitleLabel.backgroundColor = getColor(58, 206, 248, 1);
        cell.headTitleLabel.textColor = [UIColor whiteColor];
        cell.headTitleLabel.layer.cornerRadius = 10;
        cell.headTitleLabel.layer.masksToBounds = YES;
        
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.headTitleLabel.text = array[indexPath.row];
    cell.headImage.image = [UIImage imageNamed:pic[indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        //我的成就
        if (_isLogin) {
            YJMyAchievementViewController *myAchieveVC = [[YJMyAchievementViewController alloc] init];
            [self.navigationController pushViewController:myAchieveVC animated:YES];
        }else{
          
            YJLoginPageViewController *loginPageVC = [[YJLoginPageViewController alloc] init];
            [self.navigationController pushViewController:loginPageVC animated:YES];
        }
        
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            //意见
          
            if (_isLogin) {
                YJSuggestionViewController *loginPageVC = [[YJSuggestionViewController alloc] init];
                [self.navigationController pushViewController:loginPageVC animated:YES];
            }else{
                
                YJLoginPageViewController *loginPageVC = [[YJLoginPageViewController alloc] init];
                [self.navigationController pushViewController:loginPageVC animated:YES];
            }
 
            
        }
        if (indexPath.row == 1) {
            //关于我们
            YJAboutUsViewController *yjaboutUsVC = [[YJAboutUsViewController alloc] init];
            [self.navigationController pushViewController:yjaboutUsVC animated:YES];
        }
        if (indexPath.row == 2) {
            [self alertView];//是否清除缓存
        }
        if (indexPath.row == 3) {
            //推送设置
            YJPushSetViewController *pushSetVC = [[YJPushSetViewController alloc] init];
            [self.navigationController pushViewController:pushSetVC animated:YES];
        }
    }
    if (_isLogin) {
     //已登录
        if (indexPath.section == 2) {
            //退出登录
            
            [self outOfTheLogin];
        }
 
        
    }else{
     
    }
    
}

#pragma mark -- 弹出框 确定是否清除缓存
- (void)alertView{
    
    float tmpSize=[[SDImageCache sharedImageCache] getSize] / 1024.0;
    
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"清理缓存(%.2fkb)",tmpSize] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[MBHUDDIY getInstent]show];
        [[SDImageCache sharedImageCache] clearDisk];
        [self performSelector:@selector(makeSureClear) withObject:nil afterDelay:1.5f];
        
    }];
    
    UIAlertAction *cancle=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    
    [alert addAction:ok];
    [alert addAction:cancle];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)makeSureClear{
    [[MBHUDDIY getInstent]stop];
    [self.tableView reloadData];
}
#pragma mark -- tableview cell的点击事件
//退出登录
- (void)outOfTheLogin{

    UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"是否确定退出登录" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *alter1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self sureOrCacel:1];
        
    }];
    UIAlertAction *alter2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self sureOrCacel:2];
    }];
    
    [alter addAction:alter1];
    [alter addAction:alter2];
    [self presentViewController:alter animated:YES completion:nil];
    
}

- (void)sureOrCacel:(NSInteger)number{
    if (number == 1) {
      NSDictionary *dic =  [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
        NSString *platStyle = dic[@"platformType"];
        if ([platStyle integerValue] == 998) {
            //退出第三方qq登录
            [self exitQQ];
        }
       else if ([platStyle integerValue] == 1) {
           //退出第三方微博登录
            [self exitWeiBo];
       }else{
           [self exitBasic];
          
       }
        //刷新信息
    }else{
        //取消
    }
}
- (void)exitQQ{
    
        [ShareSDK cancelAuthorize:SSDKPlatformTypeQQ];
        BOOL isAuthorizedWithQQ = [ShareSDK hasAuthorized:SSDKPlatformTypeQQ];
        if (!isAuthorizedWithQQ) {
          //  NSLog(@"qq退出成功");
            [self exitBasic];
        }else{
            NSLog(@"qq退出失败");
        }
    
}
- (void)exitWeiBo{
    [ShareSDK cancelAuthorize:SSDKPlatformTypeSinaWeibo];
    BOOL isAuthorizedWithSinaWeiBo = [ShareSDK hasAuthorized:SSDKPlatformTypeSinaWeibo];
    if (!isAuthorizedWithSinaWeiBo) {
      //  NSLog(@"微博退出成功");
        [self exitBasic];
    }else{
        NSLog(@"微博退出失败");
    }

}
//刷新界面
- (void)exitBasic{
    //确定
    _headButton.image = [UIImage imageNamed:@"游客2"];
    self.nameLabel.text = @"游客";
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"isLogin"];
    
    _personalizedLabel.text = @"这是一个空的签名,不错哟";
    _isLogin = NO;
    _allInfo = _nondataSource.mutableCopy;
    _allPic = _nonpicSource.mutableCopy;
    [self.tableView reloadData];
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userInfo"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userName"];
    
  


}
#pragma mark -- lazy
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, screen_size.width, screen_size.height-48) style:UITableViewStyleGrouped];
        _tableView.rowHeight = 70;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.backgroundColor = [UIColor whiteColor];
        [_tableView registerClass:[YJMyViewCell class] forCellReuseIdentifier:@"mycell"];
     
        
    }
    return _tableView;
}
- (void)refushUI{

    //判断用户是否有修改资料,没有就从登录信息里面获取
    NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    AVQuery *query = [AVQuery queryWithClassName:@"userInfo"];//取表
    [query whereKey:@"userName" equalTo:userName];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        NSDictionary *dic1 = objects.lastObject[@"data"] ;
        
        if (dic1) {
           //存在
            if (dic1[@"sign"] ) {
                _personalizedLabel.text = dic1[@"sign"];
            }else{
                _personalizedLabel.text = @"这是一个空的签名,不错哟";
            }
            if (dic1[@"headImage"]) {
            
                [_headButton sd_setImageWithURL:[NSURL URLWithString:dic1[@"headImage"]]];
            }else{
                //没有获取到图片
                [_headButton sd_setImageWithURL:nil];
                _headButton.image = [UIImage imageNamed:@"游客2"];
            }
            if (dic1[@"nickName"]) {
                self.nameLabel.text = dic1[@"nickName"];
            }else{
                self.nameLabel.text = @"请设置用户名";
                
            }
            
        }else{
            //没有修改资料,从登陆信息中获取
            NSDictionary *headImageDic =  [[NSUserDefaults standardUserDefaults]objectForKey:@"userInfo"];//第三方登陆的信息
            
            if (headImageDic[@"sign"]) {
                _personalizedLabel.text = headImageDic[@"sign"];
            }else{
                _personalizedLabel.text = @"这是一个空的签名,不错哟";
            }
  
            if (headImageDic[@"icon"]) {
                [_headButton sd_setImageWithURL:[NSURL URLWithString:headImageDic[@"icon"]]];
                
            }else{
               //没有获取到图片
                 [_headButton sd_setImageWithURL:nil];
                _headButton.image = [UIImage imageNamed:@"游客2"];
            }
            if (headImageDic[@"nickname"]) {
                self.nameLabel.text = headImageDic[@"nickname"];
            }else{
               self.nameLabel.text = @"设置用户名";
            }
        }
    }];
    _allInfo = _dataSource.mutableCopy;
    _allPic = _picSource.mutableCopy;

    [self.tableView reloadData];
    
}


@end
